<template>
  <div>
    <!-- 搜索框和筛选 -->
    <el-input placeholder="请输入学号" v-model="Sno" id="text" style="margin-right: 10px;"></el-input>
    <el-button @click="search" :icon="Search" style="margin-right: 10px;">搜索</el-button>
    <el-select v-model="cname" placeholder="请选择课程" @change="handleCourseChange" style="margin-right: 10px;">
      <el-option :value="null" :label="'所有课程'"></el-option>
      <el-option
          v-for="item in courseOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value">
      </el-option>
    </el-select>
    <el-button @click="exportToCSV" type="primary" style="margin-right: 10px;">导出成绩</el-button>
    <el-button @click="refreshData" type="warning">刷新</el-button>

    <!-- 饼状图 -->
    <div id="pieChart" style="width: 100%; height: 400px; margin-top: 20px;"></div>

    <!-- 表格和分页 -->
    <div style="padding: 20px;">
      <el-table class="currentTable" :data="pagedStudents" :header-cell-style="{ background: '#f6f9fa' }">
        <el-table-column type="selection"></el-table-column>
        <el-table-column prop="sno" label="学号"></el-table-column>
        <el-table-column prop="sname" label="姓名"></el-table-column>
        <el-table-column prop="cno" label="课程号"></el-table-column>
        <el-table-column prop="cname" label="课程名"></el-table-column>
        <el-table-column prop="score" label="成绩"></el-table-column>
      </el-table>
      <el-pagination
          background
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20]"
          :total="filteredTotal"
          layout="prev, pager, next, sizes"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange">
      </el-pagination>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRoute } from "vue-router";
import axios from "axios";
import * as echarts from "echarts";
import { Search } from "@element-plus/icons-vue";

const route = useRoute();
const id = route.query.id;
const Sno = ref('');
const cname = ref('');
const allStudents = ref([]);
const students = ref([]);
const pagedStudents = ref([]);
const courseOptions = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const filteredTotal = ref(0);

onMounted(() => {
  getAllData();
});

const getAllData = () => {
  let pageNum = 1;
  let totalPages = 1;

  const fetchPageData = (pageNum) => {
    axios.get('http://localhost:8080/getStudentScoreByClass', {
      params: {
        page: pageNum,
        size: 1000,
        tno: id,
        sno: Sno.value
      }
    })
        .then(response => {
          const data = response.data.records;
          allStudents.value = [...allStudents.value, ...data];
          totalPages = Math.ceil(response.data.total / 1000);

          if (pageNum < totalPages) {
            fetchPageData(pageNum + 1);
          } else {
            initializeData();
            drawPieChart();
          }
        })
        .catch(error => {
          window.alert('获取数据失败');
        });
  };

  fetchPageData(pageNum);
};

const initializeData = () => {
  const courseNames = allStudents.value.map(item => item.cname);
  const uniqueCourseNames = [...new Set(courseNames)];
  courseOptions.value = uniqueCourseNames.map(cname => ({
    label: cname,
    value: cname
  }));

  students.value = allStudents.value;
  filteredTotal.value = students.value.length;
  updatePagedStudents();
};

const updatePagedStudents = () => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = currentPage.value * pageSize.value;
  pagedStudents.value = students.value.slice(startIndex, endIndex);
};

const handleCurrentChange = (pageNum) => {
  currentPage.value = pageNum;
  updatePagedStudents();
};

const handleSizeChange = (pagesize) => {
  pageSize.value = pagesize;
  updatePagedStudents();
};

const search = () => {
  students.value = allStudents.value.filter(student => {
    const matchesSno = Sno.value ? student.sno.includes(Sno.value) : true;
    const matchesCname = cname.value ? student.cname === cname.value : true;
    return matchesSno && matchesCname;
  });

  filteredTotal.value = students.value.length;
  currentPage.value = 1;
  updatePagedStudents();
  drawPieChart(); // 更新饼状图
};

const handleCourseChange = (selectedCourse) => {
  cname.value = selectedCourse;
  search(); // 搜索会自动触发饼状图更新
};

const drawPieChart = () => {
  const scores = students.value.map(student => student.score); // 使用筛选后的数据

  const scoreDistribution = {
    不合格: 0,
    一般: 0,
    良好: 0,
    优秀: 0
  };

  scores.forEach(score => {
    if (score < 60) scoreDistribution.不合格 += 1;
    else if (score < 76) scoreDistribution.一般 += 1;
    else if (score < 85) scoreDistribution.良好 += 1;
    else scoreDistribution.优秀 += 1;
  });

  const chartData = [
    { value: scoreDistribution.不合格, name: '不合格' },
    { value: scoreDistribution.一般, name: '一般' },
    { value: scoreDistribution.良好, name: '良好' },
    { value: scoreDistribution.优秀, name: '优秀' }
  ];

  const chart = echarts.init(document.getElementById('pieChart'));
  const option = {
    title: {
      text: '成绩分布情况',
      subtext: '成绩区间统计',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    series: [
      {
        name: '成绩分布',
        type: 'pie',
        radius: '50%',
        data: chartData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };

  chart.setOption(option);

  chart.on('click', params => {
    filterStudentsByScoreCategory(params.name);
  });
};

const filterStudentsByScoreCategory = (category) => {
  students.value = allStudents.value.filter(student => {
    if (cname.value && student.cname !== cname.value) return false;
    if (category === '不合格') return student.score < 60;
    if (category === '一般') return student.score >= 60 && student.score < 76;
    if (category === '良好') return student.score >= 76 && student.score < 85;
    if (category === '优秀') return student.score >= 85;
    return false;
  });

  filteredTotal.value = students.value.length;
  currentPage.value = 1;
  updatePagedStudents();
};

const exportToCSV = () => {
  const headers = ['学号', '姓名', '课程号', '课程名', '成绩'];
  const rows = students.value.map(student => [
    student.sno,
    student.sname,
    student.cno,
    student.cname,
    student.score
  ]);

  const csvContent = [headers, ...rows].map(row => row.join(',')).join('\n');
  const blob = new Blob([csvContent], {type: 'text/csv;charset=utf-8;'});
  const link = document.createElement('a');
  link.href = URL.createObjectURL(blob);
  link.download = '成绩数据.csv';
  link.click();
};

const refreshData = () => {
  students.value = [...allStudents.value];
  filteredTotal.value = students.value.length;
  currentPage.value = 1;
  updatePagedStudents();
  drawPieChart();
};
</script>
